// websocket mqtt的封装
import mqtt from 'mqtt'


export const connect = (url) => {
  return new Promise((resolve, reject) => {
    const wsMqtt = mqtt.connect(url)
    wsMqtt.on('connect', () => {
      const webSocketMqtt = new WebSocketMqtt(wsMqtt)
      resolve(webSocketMqtt)
    })
    wsMqtt.on('error', (error) => {
      reject(error)
    })
  })
}


// export const WEB_MSG_ORDER_ENUM = {
//   DEVICE_ALERT: 'DEVICE_ALERT'
// }

// export const TOPIC_ENUM = {
//   WEB_MSG: 'web_msg'
// }


 /**
  * @param {Object} mqtt实例
  */
class WebSocketMqtt {
  constructor(mqtt) {
    this.client = mqtt
    this.subscribeList = []
    this.subscribeCountList = []
    this.newsList = []
  }

  // 订阅主题
  subscribe(topic) {
    if (!this.subscribeList.includes(topic)) {
      this.subscribeList.push(topic)
      this.subscribeCountList.push(0)

      this.client.subscribe(topic, { qos: 0 })
    } else {
      const index = this.subscribeList.findIndex(item => item === topic)
      this.subscribeCountList[index] ++
    }
  }

  // 取消订阅主题
  unsubscribe(topic) {
    if (this.subscribeList.includes(topic)) {
      const index = this.subscribeList.findIndex(item => item === topic)
      // this.subscribeList = this.subscribeList.splice(index, 1)

      this.subscribeCountList[index]--

      if (!this.subscribeCountList[index]) {
        this.subscribeList = this.subscribeList.splice(index, 1)
        this.subscribeCountList = this.subscribeCountList.splice(index, 1)

        this.client.unsubscribe(topic)
      }
    }
  }

  // 监听订阅主题的信息
  getMessage(currentTopic,type, callback) {
    this.client.on('message', (topic, message) => {
      const data = JSON.parse(message)

      if (!this.subscribeList.includes(currentTopic)) {
        throw new Error(`当前订阅的主题${topic}尚未注册`)
      } else if (currentTopic === topic && type === data.webMsgOrderEnum) {
        const { msgTitle, msgContent, id } = data
        this.newsList.unshift({ title: msgTitle, content: msgContent, id: id })
        callback({ topic, data })
        }
      })
  }
  addListenClose(callback) {
    this.client.on('close', () => {
      callback()
    })
  }
}
